package com.xiaoxiong.text;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xiaoxiong.bean.ScheduleCourseData;
import com.xiaoxiong.bean.Weeks;
import com.xiaoxiong.database.OperateFormSyllabus;

/**
 * 
 * @ClassName: SecheduleActivity 
 * @Description: 课程表的Activity
 * @author xiaoxiong
 * @date 2016年5月4日 下午9:29:47 
 *
 */
public class SecheduleActivity extends BaseActivity implements
		OnClickListener, OnTouchListener {

	/**
	 * 上下文
	 */
	private Context mContext;
	/**
	 * 返回按钮
	 */
	private TextView back;
	/**
	 * 显示选择哪一周
	 */
	private TextView tv_week_pull;
	/**
	 * 显示第几周
	 */
	private TextView topWeek;
	/**
	 * 下拉列表(选择查看哪一周的课程)
	 */
	private WeekList weekList;
	/**
	 * 周数
	 */
	private Weeks weeks;
	/**
	 * 表示今天是第几周
	 */
	private int thisWeek;
	/**
	 * 显示课程数据的背景
	 */
	private List<TextView> courseLists;
	/**
	 * 课程数据
	 */
	private List<ScheduleCourseData> CourseDatas = new ArrayList<ScheduleCourseData>();

	/**
	 * 获取屏幕宽高用到的
	 */
	DisplayMetrics dm = new DisplayMetrics();
	int height;
	int gridHeight;

	/** 第一个无内容的格子 */
	private TextView empty;
	/** 每星期的格子 */
	private TextView monColum;
	private TextView tueColum;
	private TextView wedColum;
	private TextView thrusColum;
	private TextView friColum;
	private TextView satColum;
	private TextView sunColum;
	/** 课程表body部分布局 */
	private RelativeLayout course_table_layout;
	/** 课程格子平均宽度 **/
	private int aveWidth;

	// 各种颜色的背景
	private final static int[] background = { R.color.course_info_blue,
			R.color.course_info_orange, R.color.course_info_red,
			R.color.course_info_chartreuse, R.color.course_info_navy,
			R.color.course_info_purple2, R.color.course_info_firebrick,
			R.color.course_info_darkgreen, R.color.course_info_darkyellow,
			R.color.course_info_purple, R.color.course_info_black2,
			R.color.course_info_blue2, R.color.course_info_purple3,
			R.color.course_info_darkred, R.color.course_info_green,
			// 以下颜色跟上面重复
			R.color.course_info_purple, R.color.course_info_firebrick,
			R.color.course_info_darkgreen };

	private SharedPreferences nb_school_message;
	private LoadingDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.stu_sechedule);

		mContext = this;
		judge();
		initData();
		initView();
		getData();

	}

	// 判断是不是第一次进入该界面
	private void judge() {
		nb_school_message = this.getSharedPreferences("test",
				Context.MODE_PRIVATE);
		boolean is = nb_school_message.getBoolean("isFinSeche", true);
		//如果是第一次进入，则要先登录去拿取信息，否则可直接从本地数据库查看
		if (true) {
			dialog = new LoadingDialog(this, "\n第一次进入无信息\n导入中。。。");
			dialog.setCanceledOnTouchOutside(false);
			dialog.show();
			//设置用户名密码
			String nowUsername = "你的学号";
			String nowPassword = "你的密码";
			//登录
			new LoginServer(this, loginHandler, nb_school_message, nowUsername,
					nowPassword).doLogin();
		}
	}

	/**
	 * 
	* @Title: initData 
	* @Description: 初始化数据
	* @param 
	* @return void
	* @throws
	 */
	private void initData() {

		//获取显示今天是第几周的textview
		topWeek = (TextView) findViewById(R.id.week);
		//开启一个子线程去获取周数
		new DateThread(topWeek).start();

		// 获得列头的控件，即星期一、星期二、星期三。。。。
		empty = (TextView) findViewById(R.id.test_empty);
		monColum = (TextView) findViewById(R.id.test_monday_course);
		tueColum = (TextView) findViewById(R.id.test_tuesday_course);
		wedColum = (TextView) findViewById(R.id.test_wednesday_course);
		thrusColum = (TextView) findViewById(R.id.test_thursday_course);
		friColum = (TextView) findViewById(R.id.test_friday_course);
		satColum = (TextView) findViewById(R.id.test_saturday_course);
		sunColum = (TextView) findViewById(R.id.test_sunday_course);
		// 课表内容
		course_table_layout = (RelativeLayout) findViewById(R.id.test_course_rl);
		//获取周数的数组
		weeks = new Weeks();
		//创建下拉列表
		weekList = new WeekList(this, weekHandler);
		//为下拉列表设置内容（周数）
		weekList.addItems(weeks.getWeeks());
		//显示查看第几周的下拉列表
		tv_week_pull = (TextView) findViewById(R.id.week_pull_down);
		tv_week_pull.setOnTouchListener(this);
		back = (TextView) findViewById(R.id.back);
		back.setOnClickListener(this);

		courseLists = new ArrayList<TextView>();

	}

	/**
	 * 
	* @Title: initView 
	* @Description: 初始化课表视图
	* @param 
	* @return void
	* @throws
	 */
	private void initView() {
		// 获取屏幕的宽度高度
		this.getWindowManager().getDefaultDisplay().getMetrics(dm);
		// 屏幕宽度
		int width = dm.widthPixels;
		// 平均宽度
		int aveWidth = width / 8;

		// 设置第一个空白格子宽度
		empty.setWidth(aveWidth * 3 / 4);

		//设置每个课程格子宽度
		monColum.setWidth(aveWidth * 33 / 32 + 1);
		tueColum.setWidth(aveWidth * 33 / 32 + 1);
		wedColum.setWidth(aveWidth * 33 / 32 + 1);
		thrusColum.setWidth(aveWidth * 33 / 32 + 1);
		friColum.setWidth(aveWidth * 33 / 32 + 1);
		satColum.setWidth(aveWidth * 33 / 32 + 1);
		sunColum.setWidth(aveWidth * 33 / 32 + 1);
		this.aveWidth = aveWidth;
		// 屏幕高度
		height = dm.heightPixels;
		// 平均高度
		gridHeight = height / 12;

		// 设置课表界面
		// 竖直方向16个格子
		for (int i = 1; i <= 16; i++) {
			// 水平方向8个格子(包括第一列的节数)
			for (int j = 1; j <= 8; j++) {

				TextView tx = new TextView(this);
				//给每个格子设置一个唯一的id，方便后面其他格子与其对齐
				tx.setId((i - 1) * 8 + j);
				// 除了最后一列，都使用course_text_view_bg背景（最后一列没有右边框）
				tx.setBackground(getResources().getDrawable(
						R.color.course_text_view_bg));
				// 相对布局参数
				RelativeLayout.LayoutParams rp = new RelativeLayout.LayoutParams(
						aveWidth * 33 / 32 + 1, gridHeight);
				// 文字对齐方式
				tx.setGravity(Gravity.CENTER);
				// 字体样式
				tx.setTextAppearance(this, R.style.courseTableText);
				// 如果是第一列，需要设置课的序号（1 到 12）
				if (j == 1) {
					//为第一列设置1,2,3.。。等字符，表示第几节课
					tx.setText(String.valueOf(i));
					rp.width = aveWidth * 3 / 4;
					// 设置他们的相对位置
					if (i == 1) {
						rp.addRule(RelativeLayout.BELOW, empty.getId());
					} else {
						rp.addRule(RelativeLayout.BELOW, (i - 1) * 8);
					}
				} else {
					//在id为（(i - 1) * 8 + j - 1）的格子的右边，上对齐
					rp.addRule(RelativeLayout.RIGHT_OF, (i - 1) * 8 + j - 1);
					rp.addRule(RelativeLayout.ALIGN_TOP, (i - 1) * 8 + j - 1);
					tx.setText("");
				}

				//为该textview设置刚才设置好的布局
				tx.setLayoutParams(rp);
				//将该textview加入课程表视图中
				course_table_layout.addView(tx);
			}
		}
	}

	private void addCourse(ScheduleCourseData course) {

		// 添加课程信息
		TextView courseInfo = new TextView(this);
		courseInfo.setText(course.getCourseName() + "\n" + course.getTeacher()
				+ "\n@" + course.getRoom());
		// 该textview的高度根据其节数的跨度来设置
		RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
				aveWidth * 31 / 32, (gridHeight - 5) * 2);
		// textview的位置由课程开始节数和上课的时间（day of week）确定

		rlp.topMargin = 5 + (course.getStartTime() - 1) * gridHeight;
		rlp.leftMargin = 5;
		// 偏移由这节课是星期几决定
		rlp.addRule(RelativeLayout.RIGHT_OF, course.getWeek());
		// 字体居中
		courseInfo.setGravity(Gravity.CENTER);
		// 设置一种背景颜色
		courseInfo.setBackgroundResource(background[course.getColor()]);
		// 设置字体大小
		courseInfo.setTextSize(10);
		courseInfo.setLayoutParams(rlp);
		// 设置字体颜色
		courseInfo.setTextColor(Color.WHITE);
		courseInfo.setId(course.getId() + 200);
		// 设置不透明度
		courseInfo.getBackground().setAlpha(150);
		// 给每个添加进课表的课程格子添加点击事件
		courseInfo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				TextView t = (TextView) v;
				// 获取点击的格子的相对位置，以便知道是那一节课
				int fx = t.getLeft();
				int fy = aveWidth * 3 / 4 + 5;
				int whichweek = (int) (((fx - fy) / getApplicationContext()
						.getResources().getDimension(R.dimen.cell_width)) + 1);
				// 获取格子里的信息
				String val = t.getText().toString();
				
				int count = CourseDatas.size();
				//在课程表数据中查找
				for (int i = 0; i < count; ++i) {
					ScheduleCourseData coursedata = CourseDatas.get(i);

					String value = "";
					value += (coursedata.getCourseName() + "\n"
							+ coursedata.getTeacher() + "\n@" + coursedata
							.getRoom());

					//在课程表数据中查找，如果字符串相同，并且是该周上的可，则显示出来
					if (val.equals(value) && whichweek == coursedata.getWeek()) {

						// 将点击的课程的详细信息用dialog窗口展示出来
						showCourseInfo courseInfoDialog = new showCourseInfo(
								mContext, coursedata);
						courseInfoDialog.setCanceledOnTouchOutside(false);
						courseInfoDialog.show();
						break;
					}

				}
			}
		});
		courseLists.add(courseInfo);
		course_table_layout.addView(courseInfo);
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.back:
			//点击返回按钮
			SecheduleActivity.this.finish();
			break;
		}
	}

	/**
	 * 
	* @Title: getData 
	* @Description: 从本地获取数据
	* @param 
	* @return void
	* @throws
	 */
	private void getData() {
		//获取第几周
		thisWeek = nb_school_message.getInt("thisWeek", 0);
		tv_week_pull.setText("第" + thisWeek + "周(本周)");
		//获取该周的课程数据并显示出来
		setCourse(thisWeek);
	}

	/**
	 * 
	* @Title: setCourse 
	* @Description: 根据传入的周数显示相应的课程
	* @param @param whichWeek
	* @return void
	* @throws
	 */
	public void setCourse(int whichWeek) {
		// 先清空课表视图，防止重叠
		while (!courseLists.isEmpty()) {
			TextView tv = courseLists.get(0);
			courseLists.remove(0);
			// 设置背景为透明
			tv.setBackgroundColor(Color.TRANSPARENT);
			tv.setText("");
			tv.setClickable(false);
		}
		CourseDatas.clear();
		//在本地数据库获取课程数据
		OperateFormSyllabus ofpi = new OperateFormSyllabus(this);
		Cursor syll = ofpi.querySyllabus();

		while (syll.moveToNext()) {
			ScheduleCourseData courseData = new ScheduleCourseData(
					syll.getString(syll.getColumnIndex("course_name")),
					syll.getString(syll.getColumnIndex("course_time")),
					syll.getInt(syll.getColumnIndex("class_day")),
					syll.getString(syll.getColumnIndex("teacher")),
					syll.getString(syll.getColumnIndex("classroom")),
					syll.getInt(syll.getColumnIndex("part")), syll.getInt(syll
							.getColumnIndex("color")), syll.getString(syll
							.getColumnIndex("class_week")), syll.getInt(syll
							.getColumnIndex("id")));


			CourseDatas.add(courseData);
		}
		int count = CourseDatas.size();
		for (int i = 0; i < count; ++i) {
			ScheduleCourseData coursedata = CourseDatas.get(i);
			// 将该周的课程信息添加到课表中
			if (coursedata.isHaveThisWeek(whichWeek)) {
				addCourse(coursedata);
			}
		}

	}

	@SuppressLint("HandlerLeak")
	public Handler weekHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			Bundle bundle = msg.getData();
			String response = bundle.getString("position");

			int position = 0;

			//匹配单前周为第几周，在下拉列表中该周后面加上（本周），若选中的非本周则加上（非本周）
			for (int i = 0; i < weeks.getWeeks().length; ++i) {
				if (response.equals(weeks.getWeeks()[i])) {
					position = i + 1;
					break;
				}
			}
//			Log.d("week", position + "   " + thisWeek);
			if (position == thisWeek) {
				response += "(本周)";

			} else {
				response += "(非本周)";
			}

			tv_week_pull.setText(response);
			setCourse(position);

			weekList.dismiss();
		}
	};

	@SuppressLint("ClickableViewAccessibility")
	@Override
	public boolean onTouch(View v, MotionEvent e) {
		if (e.getAction() == MotionEvent.ACTION_UP) {

			switch (v.getId()) {
			case R.id.week_pull_down:
				//显示下拉列表
				weekList.showAsDropDown(v, thisWeek);
				break;
			}
		}

		return true;
	}

	// 登录返回的handler
	@SuppressLint("HandlerLeak")
	private Handler loginHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			Bundle bundle = msg.getData();
			boolean isLogin = bundle.getBoolean("isSuccess");
			if (isLogin) {

				//登录成功，获取课程表数据
				new GetSchedule(getApplicationContext(), personHandler).Post();
			} else {
				if (dialog != null) {
					dialog.dismiss();
				}
				Toast.makeText(getApplicationContext(), "请求失败，请检测你的网络", Toast.LENGTH_SHORT)
						.show();
			}
		}
	};

	// 登录返回的handler
	@SuppressLint("HandlerLeak")
	private Handler personHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			Bundle bundle = msg.getData();
			String result = bundle.getString("Value");
			boolean isLogin = bundle.getBoolean("isSuccess");
			if (isLogin) {

				//获取课程表数据成功，处理数据并返回当前周
				int thisWeek = new DealCourseData(result,
						getApplicationContext()).getsv();
				
				//把当前周保存起来，并保存不是第一次进来该页面，表示已经拿到数据，下次再进来可直接从本地拿数据，不用去登录
				Editor editor = nb_school_message.edit();
				editor.putInt("thisWeek", thisWeek);
				editor.putBoolean("isFinSeche", false);
				editor.commit();
				//把获得的课程数据显示出来
				getData();
			} else {
				Toast.makeText(getApplicationContext(), "请求失败，请检测你的网络", Toast.LENGTH_SHORT)
						.show();
			}
			if (dialog != null) {
				dialog.dismiss();
			}
		}
	};

}